package com.genia.toolbox.web.gwt.form.client.manager;

import java.util.ArrayList;


/**
 * a {@link java.util.List} of {@link FormManager} that will record the elements to the
 * upper {@link FormManager}.
 */
@SuppressWarnings("serial")
public class RecordableFormManagerList
    extends ArrayList<FormManager>
{

  /**
   * the {@link FormManager} that will record the elements of the {@link java.util.List}.
   */
  private final FormManager mainFormManager;



  /**
   * constructor.
   * 
   * @param mainFormManager
   *          the {@link FormManager} that will record the elements of the
   *          {@link java.util.List}
   */
  public RecordableFormManagerList(final FormManager mainFormManager)
  {
    this.mainFormManager = mainFormManager;
  }



  /**
   * Appends the specified element to the end of this list.
   * 
   * @param formManager
   *          element to be appended to this list.
   * @return <tt>true</tt> (as per the general contract of Collection.add).
   */
  @Override
  public boolean add(final FormManager formManager)
  {
    mainFormManager.recordNewSubFormManager(formManager);
    return super.add(formManager);
  }



  /**
   * Removes all of the elements from this list. The list will be empty after
   * this call returns.
   */
  @Override
  public void clear()
  {
    for (final FormManager formManager : this) {
      mainFormManager.releaseSubFormManager(formManager);
    }
    super.clear();
  }



  /**
   * Removes a single instance of the specified element from this list, if it is
   * present (optional operation). More formally, removes an element <tt>e</tt>
   * such that <tt>(o==null ? e==null :
   * o.equals(e))</tt>, if the list contains one or more such elements. Returns
   * <tt>true</tt> if the list contained the specified element (or equivalently,
   * if the list changed as a result of the call).
   * <p>
   * 
   * @param formManager
   *          element to be removed from this list, if present.
   * @return <tt>true</tt> if the list contained the specified element.
   */
  @Override
  public boolean remove(final Object formManager)
  {
    final boolean isRemoved = super.remove(formManager);
    if (isRemoved) {
      mainFormManager.releaseSubFormManager((FormManager) formManager);
    }
    return isRemoved;
  }
}
